package com.moli.iov.open.web.controller;

import com.moli.iov.base.model.dto.res.VehicleTboxResDto;
import com.moli.iov.base.remote.IVehicleBaseRemoteService;
import com.moli.iov.base.remote.IVehicleTboxRemoteService;
import com.moli.iov.cache.RedisUtil;
import com.moli.iov.open.model.vo.res.VehicleStatusOpenVO;
import com.moli.iov.protocol.model.realtime.RealTimeInfo;
import com.moli.iov.protocol.model.realtime.RealTimeInfoReq;
import com.moli.iov.real.model.res.VehicleStatusDto;
import com.moli.iov.real.service.IRealService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/real")
public class RealController extends BaseController {

    @Reference(group = "${service.group}", check = false)
    IVehicleTboxRemoteService vehicleTboxRemoteService;

    @Reference(group = "${service.group}", check = false)
    IVehicleBaseRemoteService vehicleBaseRemoteService;

    @Reference(group = "${service.group}", check = false)
    IRealService realService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据车架号集合获取电量map集合
     * @param vinList
     * @return
     */
    @RequestMapping("/soc/map")
    public RestResponse<Map<String, Byte>> getSocMapByVin(@RequestParam(required = false) List<String> vinList) {
        log.info("查询电量，{}",vinList);
        if (vinList == null || vinList.size() < 1) {
            return RestResponse.failure("参数不能为null");
        }
        try {
            Map<String, Byte> result = new HashMap<>();
            RestResponse<List<RealTimeInfo>> res = realService.listRealTimeInfo(vinList);
            if (res != null && res.getData() != null && res.getData().size() > 0) {
                List<RealTimeInfo> list = res.getData();
                for (RealTimeInfo realTimeInfo : list) {
                    if (realTimeInfo != null
                            && !StringUtils.isEmpty(realTimeInfo.getVin())
                            && realTimeInfo.getRealTimeInfoReq() != null
                            && realTimeInfo.getRealTimeInfoReq().getVehicleAllReq() != null) {
                        result.put(realTimeInfo.getVin(),realTimeInfo.getRealTimeInfoReq().getVehicleAllReq().getSoc());
                    }
                }
            }
            return RestResponse.success(result);
        } catch (Exception e) {
            log.error("实时服务查询异常,{}", e);
            return RestResponse.failure("查询错误");
        }
    }


    @RequestMapping("/dynamicState/map")
    public RestResponse<Map<String, Integer>> getDynamicStateMapByVin(@RequestParam(required = false) List<String> vinList) {
        log.info("查询动力状态，{}",vinList);

        long start = System.currentTimeMillis();
//        if (vinList == null || vinList.size() <= 0) {
//            return RestResponse.failure("参数不能为null");
//        }
        try {
            Map<String, Integer> result = new HashMap<>();
            RestResponse<Map<String,Integer>> res = realService.getDynamicStateMap(vinList);
//            log.info("查询动力状态,{}",JsonUtils.toJson(result));
            long start1 = System.currentTimeMillis();
            log.info("查询动力状态执行时长：{}ms",(System.currentTimeMillis()-start1));
            return res;
        } catch (Exception e) {
            log.error("实时服务查询异常,{}", e);
            return RestResponse.failure("查询错误");
        }
    }

    @RequestMapping("/all")
    public RestResponse<List<VehicleStatusOpenVO>> listVehicleStatus() {

        long start = System.currentTimeMillis();

        List<String> vinList = null;
        RestResponse<List<String>> result = vehicleBaseRemoteService.listVinByCompanyId(null);
        if (result != null && result.flag && result.getData() != null && result.getData().size() > 0) {
            vinList = result.getData();
        }

        List<VehicleStatusOpenVO> list = new ArrayList<>();
//        Map<String,String>  deviceMap = getDeviceMap(vinList);

        long start1 = System.currentTimeMillis();
        log.info("查询所有车辆，耗时:{}", (start1 - start));
        RestResponse<Map<String, VehicleStatusDto>> res = realService.getVehicleStatusByVin(vinList);
        if (res != null && res.flag && res.getData() != null) {
            for (VehicleStatusDto datum : res.getData().values()) {
                if (datum != null) {
                    VehicleStatusOpenVO vo = new VehicleStatusOpenVO();
//                    vo.setDeviceId(deviceMap.get(datum.getVin()));
                    vo.setGpsOdo((int) Math.ceil(datum.getGpsOdo()));
                    vo.setMeterOdo((int) Math.ceil(datum.getMeterOdo()));
                    vo.setOdo((int) Math.ceil(datum.getOdo()));
                    vo.setVin(datum.getVin());
                    list.add(vo);
                }
            }
        }
        long end = System.currentTimeMillis();
        log.info("查询所有车辆状态，耗时:{}", (end - start1));
        return RestResponse.success(list);
    }

    /**
     * 查询车辆实时状态接口
     *
     * @param vinList
     * @return
     */
    @RequestMapping("/list")
    public RestResponse<List<VehicleStatusOpenVO>> listVehicleStatus(@RequestParam(required = false) List<String> vinList) {
        if (vinList == null || vinList.size() < 1) {
            if (vinList == null || vinList.size() < 1) {
                RestResponse<List<String>> res = vehicleBaseRemoteService.listVinByCompanyId(null);
                if (res != null && res.flag && res.getData() != null && res.getData().size() > 0) {
                    vinList = res.getData();
                }
            }
        }


        List<VehicleStatusOpenVO> list = new ArrayList<>();

        Map<String, String> deviceMap = getDeviceMap(vinList);

        RestResponse<Map<String, VehicleStatusDto>> res = realService.getVehicleStatusByVin(vinList);
        if (res != null && res.flag && res.getData() != null) {
            for (VehicleStatusDto datum : res.getData().values()) {
                if (datum != null) {
                    VehicleStatusOpenVO vo = new VehicleStatusOpenVO();
                    vo.setDeviceId(deviceMap.get(datum.getVin()));
                    vo.setGpsOdo((int) Math.ceil(datum.getGpsOdo()));
                    vo.setMeterOdo((int) Math.ceil(datum.getMeterOdo()));
                    vo.setOdo((int) Math.ceil(datum.getOdo()));
                    vo.setVin(datum.getVin());
                    list.add(vo);
                }
            }
        }
//        for (String vin : vinList) {
//            VehicleStatusOpenVO vo = new VehicleStatusOpenVO();
//            vo.setDeviceId("123");
//            vo.setGpsOdo(11.1);
//            vo.setMeterOdo(12.2);
//            vo.setOdo(1.1);
//            vo.setVin(vin);
//            list.add(vo);
//        }

        return RestResponse.success(list);
    }

    private Map<String, String> getDeviceMap(List<String> vinList) {
        RestResponse<List<VehicleTboxResDto>> tboxResult = vehicleTboxRemoteService.listVehicleTboxList(vinList);
        if (tboxResult != null && tboxResult.getData() != null && tboxResult.getData().size() > 0) {
            List<VehicleTboxResDto> list = tboxResult.getData();
            Map<String, String> map = list.stream().collect(Collectors.toMap(VehicleTboxResDto::getVin, VehicleTboxResDto::getDeviceId));
            return map;
        }
        return new HashMap<>();
    }

    public static void main(String[] args) {
//        Map<String, VehicleStatusOpenVO> map = new HashMap<>();
//        VehicleStatusOpenVO vo = new VehicleStatusOpenVO();
//        vo.setDeviceId("123");
////        vo.setGpsOdo(11.1);
////        vo.setMeterOdo(12.2);
////        vo.setOdo(1.1);
//        vo.setVin("111");
//        map.put("111", vo);
//        System.out.println(JsonUtils.toJson(RestResponse.success(map)));

        List<String> list = new ArrayList<>();
        list.add("123");
        System.out.println(list);

    }
}
